package com.gsafety.wellsfort.common.util;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;


public class SHA256whitRSA {

    public static final String SIGNATURE_ALGORITHM = "SHA256withRSA";

    /**
     * 签名
     * @param content
     *            明文
     * @return
     */
    public static String sign(String content,String privateKey) {
        try {
            PrivateKey priKey = SignatureUtil.getPrivateKeyFromPKCS8("RSA", new ByteArrayInputStream(privateKey.getBytes()));
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(priKey);
            if (StringUtil.isEmpty("UTF-8")) {
                signature.update(content.getBytes());
            } else {
                signature.update(content.getBytes("UTF-8"));
            }
            byte[] signed = signature.sign();
            return new String(Base64.encodeBase64(signed));
        } catch (Exception var7) {
            throw new RuntimeException("RSAcontent = " + content + "; charset = " + "UTF-8", var7);
        }
    }

    /**
     * SHA256whitRSA验签
     * @param content
     *            明文
     * @param sign
     *            密文
     */
    public static boolean rsa256CheckContent(String content, String sign,String publicKey) throws Exception {

        try {
            PublicKey pubKey = SignatureUtil.getPublicKeyFromX509("RSA",
                    new ByteArrayInputStream(publicKey.getBytes()));
            Signature signature = Signature
                    .getInstance("SHA256WithRSA");
            signature.initVerify(pubKey);
            signature.update(content.getBytes("UTF-8"));
            return signature.verify(Base64.decodeBase64(sign.getBytes()));
        } catch (Exception e) {
            throw new RandException(-1,"验签异常");
        }
    }
}
